package job.manager.db.dao;

import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import job.manager.db.ec.JobEB;
import job.manager.db.ec.ProfileJobMapperEB;
import job.manager.db.ec.ProfilesEB;


/**
 *  DAO class is responsible for communcation with the
 *  database regarding jobs.
 */
public class JobDAO {

    private EntityManager em;

    public JobDAO() {

    }

    public JobDAO(EntityManager em){
        this.em = em;
    }

    public JobEB getJob(Integer pk) {
        return em.find(JobEB.class, pk);
    }

    public JobEB insert(JobEB job){
        if(job != null){
            em.persist(job);
            em.flush();
            if( em.contains(job)){
                return job;
            }
        }
        return null;
    }

    public int update(JobEB job){
        if( job != null){
            JobEB j = em.merge(job);
            em.flush();
            return 1;
        }
        return 0;
    }


    public int delete(JobEB job){
        if(job != null){
            JobEB j = em.merge(job);
            em.remove(j);
            return 1;
        }
        return 0;
    }

    public int delete(Integer pk){
        if(pk != null){
            return this.delete(em.find(JobEB.class, pk));
        }
        return 0;
    }

    public Collection<JobEB> getAllJobs(){
        Query q = em.createNamedQuery("JobEB.findAll");
        return q.getResultList();
    }

    public Collection<JobEB> getJobsByPid(Integer pk)
    {
        Query q= em.createNamedQuery("JobEB.findByProfile");
        q.setParameter("pid", pk);
        return q.getResultList();
    }

    public Collection<ProfilesEB> getWorkers(Integer jid)
    {
        Query q= em.createNamedQuery("ProfileJobMapperEB.findByJobId");
        q.setParameter("jid", jid);
        q.setParameter("accepted", true);
        return q.getResultList();
    }

    public Collection<JobEB> getJobsByCustomer(ProfilesEB customerId)
    {
       Query q = em.createNamedQuery("JobEB.findByProfile");
       q.setParameter("customerId", customerId);
       return q.getResultList();
    }
}